import {Injectable} from '@angular/core';
import {InterfaceProvider} from "@providers/interface";
import {DialogProvider} from "@providers/dialog";
import {HttpClient, HttpHeaders} from "@angular/common/http";

/*
  百度api使用类

  1.文字转语音
*/
@Injectable()
export class BaiduProvider {

  constructor(private ifp: InterfaceProvider,
              private http: HttpClient,
              private dialog: DialogProvider) {
  }

  /**
   * 获取百度 access_token
   * @param app_id
   * @param app_secret
   * @returns {Promise<any>}
   */
  getAccessToken(): Promise<any> {
    return this.ifp.post({
      interfaceId: 'app.baidu.getAccessToken',
      data: {client_id: 'XnM3VyB2YGIOeycdTDsYWeAr', client_secret: 'a3D1n0eurrdEXjkKztggGWL0xNgFdUwd'}
    }).toPromise()
  }

  /**
   * 文字转语音
   * @param text
   * @returns {Promise<any>}
   */
  text2audio(text): Promise<any> {
    return new Promise<any>((resolve) => {
      let text_encode = encodeURI(text);
      let params = {
        tex: text_encode || '',
        cuid: 'JL',
        ctp: '1',
        lan: 'zh',
        per: '0',//发音人选择, 0为普通女声，1为普通男生，3为情感合成-度逍遥，4为情感合成-度丫丫，默认为普通女声
        spd: '5',//语速，取值0-15，默认为5中语速
        vol: '15',//音量，取值0-15，默认为5中音量
        pit: '5',//音调，取值0-15，默认为5中语调
        aue: '3'
      };
      this.getAccessToken().then(v => {
        params['tok'] = v['access_token'];
        let body: any = this.buildURLSearchParams(params);
        this.http.post(
          'https://tsn.baidu.com/text2audio',
          body.toString(),
          {
            headers: new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'}),
            responseType: 'blob'
          }
        ).subscribe(v => {
          resolve(v)
        }, e => {
          this.dialog.showToast(e)
        })
      }).catch(e => this.dialog.showAlert(e));
    })
  }

  buildURLSearchParams(paramMap: Map<String, any> | any): URLSearchParams {
    let params = new URLSearchParams;
    for (let key in paramMap) {
      let val = paramMap[key];
      params.set(key, val);
    }
    return params
  }

}
